import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/stores/user'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { 
  ALL_PERMISSIONS
} from '@/constants/permissions'

// 路由配置
const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录', requiresAuth: false }
  },
  {
    path: '/',
    component: () => import('@/layouts/MainLayout.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '仪表盘', icon: 'Odometer', permission: ALL_PERMISSIONS.ADMIN_DASHBOARD_READ }
      },
      {
        path: 'users',
        name: 'Users',
        component: () => import('@/views/users/UserList.vue'),
        meta: { title: '用户管理', icon: 'User', permission: ALL_PERMISSIONS.USER_LIST }
      },

      {
        path: 'roles',
        name: 'Roles',
        component: () => import('@/views/roles/RoleList.vue'),
        meta: { title: '角色管理', icon: 'UserFilled', permission: ALL_PERMISSIONS.ROLE_READ }
      },

      {
        path: 'permissions',
        name: 'Permissions',
        component: () => import('@/views/permissions/PermissionList.vue'),
        meta: { title: '权限管理', icon: 'Lock', permission: ALL_PERMISSIONS.PERMISSION_READ }
      },

      {
        path: 'logs',
        name: 'Logs',
        component: () => import('@/views/logs/LogList.vue'),
        meta: { title: '操作日志', icon: 'Document', permission: ALL_PERMISSIONS.LOG_READ }
      },
      {
        path: 'system',
        name: 'System',
        component: () => import('@/views/system/SystemLayout.vue'),
        meta: { title: '系统设置', icon: 'Setting', permission: ALL_PERMISSIONS.ADMIN_SETTING_READ }
      },
      {
        path: 'artists',
        name: 'Artists',
        component: () => import('@/views/artists/ArtistList.vue'),
        meta: { title: '艺人管理', icon: 'User', permission: ALL_PERMISSIONS.ARTIST_LIST }
      },
      {
        path: 'performances',
        name: 'Performances',
        component: () => import('@/views/performances/PerformanceList.vue'),
        meta: { title: '演出管理', icon: 'Calendar', permission: ALL_PERMISSIONS.PERFORMANCE_LIST }
      },
      {
        path: 'floors',
        name: 'Floors',
        component: () => import('@/views/floors/FloorList.vue'),
        meta: { title: '楼层管理', icon: 'OfficeBuilding', permission: ALL_PERMISSIONS.FLOOR_LIST }
      },
      {
        path: 'venues',
        name: 'Venues',
        component: () => import('@/views/venues/index.vue'),
        meta: { title: '场馆管理', icon: 'House', permission: ALL_PERMISSIONS.VENUE_READ }
      },
      {
        path: 'votes',
        name: 'Votes',
        component: () => import('@/views/votes/VoteList.vue'),
        meta: { title: '投票管理', icon: 'Trophy', permission: ALL_PERMISSIONS.VOTE_READ }
      },
      {
        path: 'activities',
        name: 'Activities',
        component: () => import('@/views/activities/ActivityList.vue'),
        meta: { title: '活动管理', icon: 'Calendar', permission: ALL_PERMISSIONS.ACTIVITY_READ }
      },
      {
        path: 'activities/:id',
        name: 'ActivityDetail',
        component: () => import('@/views/activities/ActivityDetail.vue'),
        meta: { title: '活动详情', icon: 'View', permission: ALL_PERMISSIONS.ACTIVITY_READ, hidden: true }
      },
      {
        path: 'fun-facts',
        name: 'FunFacts',
        component: () => import('@/views/content/FunFactList.vue'),
        meta: { title: '冷知识管理', icon: 'Opportunity', permission: ALL_PERMISSIONS.CONTENT_READ }
      },
      {
        path: 'badges',
        name: 'Badges',
        component: () => import('@/views/content/BadgeList.vue'),
        meta: { title: '徽章管理', icon: 'Medal', permission: ALL_PERMISSIONS.BADGE_READ }
      },

      {
        path: 'works',
        name: 'Works',
        component: () => import('@/views/works/WorkList.vue'),
        meta: { title: '作品管理', icon: 'VideoPlay', permission: ALL_PERMISSIONS.WORK_READ }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/Profile.vue'),
        meta: { title: '个人资料', icon: 'User', permission: ALL_PERMISSIONS.PROFILE_READ }
      }
    ]
  },
  {
    path: '/403',
    name: 'Forbidden',
    component: () => import('@/views/Forbidden.vue'),
    meta: { title: '访问被拒绝' }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue'),
    meta: { title: '页面不存在' }
  }
]

const router = createRouter({
  history: createWebHistory('/admin/'),
  routes: routes as RouteRecordRaw[]
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  
  const userStore = useUserStore()
  
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 后台管理系统` : '后台管理系统'
  
  // 检查是否需要登录
  if (to.meta.requiresAuth !== false) {
    if (!userStore.isLoggedIn) {
      next('/login')
      return
    }
    
    // 如果没有用户信息，获取用户信息
    if (!userStore.user) {
      try {
        await userStore.getUserInfo()
      } catch (error) {
        next('/login')
        return
      }
    }
    
    // 检查权限
    if (to.meta.permission && !userStore.hasPermission(to.meta.permission as string)) {
      console.log('没有权限', to.meta.permission, userStore.hasPermission(to.meta.permission as string), userStore.user)
      next('/403')
      return
    }
  }
  
  next()
})

router.afterEach(() => {
  NProgress.done()
})

export default router